import './SetProjectTheme.scss'

import { useRef } from 'react'
import { useRequest } from 'alova/client'
import { Graph, Shape } from '@antv/x6'
import { register } from '@antv/x6-react-shape'
import { Http } from '../../Utils/Api'
import { drawerStore } from '../../Config/zustand'
import { Decrypt } from '../../Utils/IndexedDB'
import { useMount } from 'ahooks'

const connecting = {
    router: 'manhattan',
    connector: { name: 'rounded', args: { radius: 8 } },
    anchor: 'center',
    connectionPoint: 'anchor',
    allowBlank: false,
    snap: { radius: 20 },
}

const attr = { attrs: { line: { stroke: '#A2B1C3', strokeWidth: 2, targetMarker: { name: 'block', width: 12, height: 8 } } }, zIndex: 0 }

const SetProjectTheme = () => {
    const X6Box = useRef()
    const { updateDrawer } = drawerStore()

    const { send } = useRequest(data => Http(data), { immediate: false })
    const getData = () => {
        send({ method: 'get', url: 'getProject', params: { uuid: 'Process/a8440b66-138c-400a-854d-97b9cb78342a@后台主题' } }).then(async res => {
            const data = await Decrypt(res)
            renderFlow(data)
        })
    }

    const renderFlow = (data) => {
        if (X6Box.current) {
            const graph = new Graph({
                interacting: false,
                container: X6Box.current,
                grid: true,
                background: { color: '#ffffff' },
                connecting: { ...connecting, createEdge() { return new Shape.Edge(attr) }, validateConnection({ targetMagnet }) { return !!targetMagnet } },
            })
            graph.fromJSON(data)
            graph.centerContent()
        } else setTimeout(() => renderFlow(data), 500);
    }

    const CustomComponent = ({ node }) => {
        const { text, waring, params } = node.attrs.text
        return (
            <div
                className={`custom-react-node${waring ? ' waring' : ''}`}
                style={params ? { cursor: 'pointer' } : {}}
                onClick={() => { if (params) updateDrawer({ title: text, type: 'SetAdminTheme', width: 560, data: { type: params } }) }}
            >
                {text}
            </div>
        )
    }

    register({ shape: 'custom-react-node', component: CustomComponent })

    useMount(() => { getData() })

    return (
        <div className='SetProjectTheme'>
            <div className='SetProjectTheme__CHarts' ref={X6Box} />
        </div>
    );
};

export default SetProjectTheme;